import { getContextOrSetDefault, removeContext, setContext } from './contextUtil'

export function confirmDialog (content, success, cancel) {
  if (typeof content == 'string') {
    content = {
      content
    }
  }
  uni.showModal({
    title: '提示',
    ...content,
    success (res) {
      if (res.confirm) {
        success && success()
      } else if (res.cancel) {
        cancel && cancel()
      }
    }
  })
}

export function showSuccess (msg) {
  uni.showToast({
    icon: 'success',
    title: msg
  })
}

export function showToast (msg) {
  uni.showToast({
    icon: 'none',
    title: msg
  })
}

export function showLoading (msg) {
  uni.showLoading({
    title: msg || '加载中'
  })
}

export function hideLoading () {
  uni.hideLoading()
}

const loadingKey = '__loading__'

export async function wrapLoading (callback) {
  const loading = getContextOrSetDefault(loadingKey, () => false)
  if (loading) {
    return
  }
  setContext(loadingKey, true)
  showLoading()
  try {
   return await callback()
  } finally {
    removeContext(loadingKey)
    hideLoading()
  }
}